package com.lishide.scrollrecyclerview;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.lishide.recyclerview.scroll.SpaceItemDecoration;
import com.lishide.recyclerview.scroll.listener.OnItemClickListener;
import com.lishide.recyclerview.scroll.listener.OnItemKeyListener;
import com.lishide.recyclerview.scroll.listener.OnItemLongClickListener;
import com.lishide.recyclerview.scroll.listener.OnItemSelectedListener;
import com.lishide.scrollrecyclerview.coreokhttp.parser.Callback;
import com.lishide.scrollrecyclerview.coreokhttp.parser.impl.StringParser;
import com.lishide.scrollrecyclerview.json.JSONParser;
import com.lishide.scrollrecyclerview.utils.NetUtil2;
import com.lishide.scrollrecyclerview.utils.PhoneInfoUtils;
import com.lishide.scrollrecyclerview.utils.UIApplication;
import com.lishide.scrollrecyclerview.utils.WiFiUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import static com.lishide.scrollrecyclerview.NetBroadcastReceiver.ACTION_TETHER_STATE_CHANGED;

/**
 * 横向网格布局示例
 * 数据源为设备中所有 App
 * 演示 item 选定监听、item 点击监听、item 长按监听、遥控器其他按键监听
 */
public class StagGridActivity extends BaseActivity {
    private static final String TAG = StagGridActivity.class.getSimpleName();
    private RecyclerView mScrollRecyclerView;
    private TextView tvTime;
    private TextView wifipass;
    private TextView wifiname;

    private TextView weather;

    private TextView boxIdView;
    private DisplayImageOptions options;
    private Context context;
    private ImageView bgimage;
    WiFiUtils wiFiUtils;
    List<AppModel> mList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        options = new DisplayImageOptions.Builder()
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                .cacheOnDisk(true)
                .cacheInMemory(false)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();

        UIApplication.initImageLoader(this);

        setContentView(R.layout.activity_stag_grid);

        UMConfigure.setLogEnabled(true);
        UMConfigure.init(this, "5b617fea8f4a9d0c40000044", "Umeng", UMConfigure.DEVICE_TYPE_BOX, "1fe6a20054bcef865eeb0991ee84525b");


        context = this;
        // 初始化 ScrollRecyclerView
        mScrollRecyclerView = (RecyclerView) findViewById(R.id.scroll_recycler_view);
        // 获得数据，数据源为设备中所有 App
//        List<AppBean> mList = getAllApk();

        mList = new AppDataManage(this).getLaunchAppList();


        // 初始化适配器
        AppBeanAdapter adapter = new AppBeanAdapter(this, mList);
        // 设置动画
        mScrollRecyclerView.setItemAnimator(new DefaultItemAnimator());
        // 设置布局管理器：瀑布流式
        mScrollRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(5,
                StaggeredGridLayoutManager.HORIZONTAL));
        // 根据需要设置间距等
        int right = (int) getResources().getDimension(R.dimen.dp_20);
        int bottom = (int) getResources().getDimension(R.dimen.dp_20);
        RecyclerView.ItemDecoration spacingInPixel = new SpaceItemDecoration(right, bottom);
        mScrollRecyclerView.addItemDecoration(spacingInPixel);
        // 关联适配器
        mScrollRecyclerView.setAdapter(adapter);
        adapter.setOnItemSelectedListener(mOnItemSelectedListener);
        adapter.setOnItemClickListener(mOnItemClickListener);
        adapter.setOnItemLongClickListener(mOnItemLongClickListener);
        adapter.setOnItemKeyListener(mOnItemKeyListener);
        tvTime = (TextView) findViewById(R.id.title_time);
        wifiname = (TextView) findViewById(R.id.title_wifi);
        wifipass = (TextView) findViewById(R.id.title_wifi_pass);
        weather = (TextView) findViewById(R.id.title_weather);
        boxIdView = (TextView) findViewById(R.id.boxid);
        bgimage = (ImageView) findViewById(R.id.bgimage);


        bgimage.setAlpha(0.9f);
//        bgimage.setColorFilter(Color.parseColor("#FFF"), PorterDuff.Mode.LIGHTEN);


        new TimeThread().start(); //启动新的线程


        MyThread m = new MyThread();
        new Thread(m).start();

        NetBroadcastReceiver receiver = new NetBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        filter.addAction(WIFI_AP_STATE_CHANGED_ACTION);
        filter.addAction(ACTION_TETHER_STATE_CHANGED);
        this.registerReceiver(receiver, filter);//注册

        receiver.onReceive(this,this.getIntent() );//接收

        getWether();

        getBoxInfo();





    }

    public void getBoxInfo() {

        OkHttpClient okHttpClient = new OkHttpClient();
        StringParser parser = new StringParser();

        String url = "http://gw.dtlx.ltd/box/info?macAddress=" + PhoneInfoUtils.getLocalMac(context);
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE 52e6c01a15eb4302b71e9225643e1cf0").build();

        okHttpClient.newCall(request).enqueue(new Callback<String>(parser) {
            @Override
            public void onResponse(Object t) {
                try {

                    Log.d("box", "onResponse: " + t);
                    if (t != null) {

                        Map data = JSONParser.StringToJSONObjectParser(t.toString());
                        ;
                        if (data.containsKey("id")) {


                            Message msg = new Message();
                            Bundle b = new Bundle();// 存放数据
                            b.putString("boxId", data.get("id").toString());
                            b.putString("logo", data.get("logo") != null ? data.get("logo").toString() : "");
                            msg.setData(b);
                            msg.what = 4;
                            mHandler.sendMessage(msg); // 向Handler发送消息,更新UI


                            Log.d("box", "onResponse: " + data.get("boxId").toString() + "℃");


                        }

                    }
                } catch (Exception e) {

                }

            }

        });
    }

    public void setImageURL(final String path) {
        //开启一个线程用于联网
        new Thread() {
            @Override
            public void run() {
                try {
                    //把传过来的路径转成URL
                    URL url = new URL(path);
                    //获取连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //使用GET方法访问网络
                    connection.setRequestMethod("GET");
                    //超时时间为10秒
                    connection.setConnectTimeout(10000);
                    //获取返回码
                    int code = connection.getResponseCode();
                    if (code == 200) {
                        InputStream inputStream = connection.getInputStream();
                        //使用工厂把网络的输入流生产Bitmap
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        //利用Message把图片发给Handler
                        Message msg = Message.obtain();
                        msg.obj = bitmap;
                        msg.what = 5;
                        mHandler.sendMessage(msg);
                        inputStream.close();
                    } else {

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    //网络连接错误

                }
            }
        }.start();
    }

    public void getWether() {

        OkHttpClient okHttpClient = new OkHttpClient();
        StringParser parser = new StringParser();

        String url = "http://jisutqybmf.market.alicloudapi.com/weather/query?city=%E8%A5%BF%E5%AE%89";
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE 52e6c01a15eb4302b71e9225643e1cf0").build();

        okHttpClient.newCall(request).enqueue(new Callback<String>(parser) {
            @Override
            public void onResponse(Object t) {
                try {

                    Log.d("getWether", "onResponse: " + t);
                    if (t != null) {

                        Map data = JSONParser.StringToJSONObjectParser(t.toString());
                        ;
                        if (data.containsKey("result")) {
                            Map result = (Map) data.get("result");


                            Message msg = new Message();
                            Bundle b = new Bundle();// 存放数据
                            b.putString("weather", result.get("weather").toString());
                            b.putString("temp", result.get("temp").toString());
                            b.putString("temphigh", result.get("temphigh").toString());
                            b.putString("week", result.get("week").toString());

                            msg.setData(b);
                            msg.what = 3;
                            mHandler.sendMessage(msg); // 向Handler发送消息,更新UI


                            Log.d("getWether", "onResponse: " + result.get("weather").toString() + "℃");


                        }

                    }
                } catch (Exception e) {

                }

            }

        });
    }

    class TimeThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;  //消息(一个整型值)
                    mHandler.sendMessage(msg);// 每隔1秒发送一个msg给mHandler
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }


    @Override
    public void onPause() {
        getWether();

        getBoxInfo();
        super.onPause();
        if (wiFiUtils != null) {
            int state = wiFiUtils.getWifiAPState();
            if (state == 13) {

                Message msg = new Message();
                Bundle b = new Bundle();// 存放数据
                b.putString("ssid", wiFiUtils.getValidApSsid());
                b.putString("password", wiFiUtils.getValidPassword());

                msg.setData(b);
                msg.what = 2;
                mHandler.sendMessage(msg); // 向Handler发送消息,更新UI
            }
        }
        MobclickAgent.onPause(this);
    }


    @Override
    public void onNetChange(int netMobile) {
        // TODO Auto-generated method stub
        try {

//            Toast.makeText(this, "netMobile=" + netMobile, Toast.LENGTH_SHORT).show();
            //在这个判断，根据需要做处理
//        boolean isNet = isNetConnect();
//
//        if (isNet) {
            Log.d("netMobile", "----------------------onNetChange: netMobile=" + netMobile);
            if (netMobile == 1) {
//                wiFiUtils.turnOnWifiAp("hellowifi", "123456789", WiFiUtils.WifiSecurityType.WIFICIPHER_WPA2);

                wifiname.setText("已连接网络");


                wifipass.setText("");
                boolean ws = wiFiUtils.setWifiApEnabledV1(context);
                Log.d("netMobile", "----------------------onNetChange: netMobile=" + netMobile + ",ws=" + ws);
                if (ws) {
//                    Message msg = new Message();
//                    Bundle b = new Bundle();// 存放数据
//                    b.putString("ssid", wiFiUtils.getValidApSsid());
//                    b.putString("password", wiFiUtils.getValidPassword());
//
//                    msg.setData(b);
//                    msg.what = 2;
//                    mHandler.sendMessage(msg); // 向Handler发送消息,更新UI


                    wifiname.setText("WiFi:" + wiFiUtils.getValidApSsid());


                    wifipass.setText("密码:" + wiFiUtils.getValidPassword());

                }


            } else {


//                Message msg = new Message();
//                Bundle b = new Bundle();// 存放数据
//                b.putString("ssid", "未连接网络");
//                b.putString("password", "");
//
//                msg.setData(b);
//                msg.what = 7;
//                mHandler.sendMessage(msg); // 向Handler发送消息,更新UI

                wifiname.setText("未连接网络");


                wifipass.setText("");
                closeApAndOpenWifi();


            }
            getWether();

            getBoxInfo();
//            if (wiFiUtils != null) {
//
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            int state = wiFiUtils.getWifiAPState();
//                            if (state == 13 ) {
//                                try {
//                                    Thread.sleep(500);
//                                } catch (InterruptedException e) {
//                                    e.printStackTrace();
//                                }
//                                Message msg = new Message();
//                                Bundle b = new Bundle();// 存放数据
//                                b.putString("ssid", wiFiUtils.getValidApSsid());
//                                b.putString("password", wiFiUtils.getValidPassword());
//
//                                msg.setData(b);
//                                msg.what = 2;
//                                mHandler.sendMessage(msg); // 向Handler发送消息,更新UI
//                            }else{
//
//                                Message msg = new Message();
//                                Bundle b = new Bundle();// 存放数据
//                                b.putString("ssid","已连接网络");
//                                b.putString("password", "");
//
//                                msg.setData(b);
//                                msg.what = 6;
//                                mHandler.sendMessage(msg); // 向Handler发送消息,更新UI
//                            }
//
//
//                        }
//                    }).start();
//
//
//                }

            super.onResume();
//            MyThread m = new MyThread();
//            new Thread(m).start();
            MobclickAgent.onResume(this);

//        }
        }catch (Exception e){


        }
    }

    private void closeApAndOpenWifi() {
        int state = wiFiUtils.getWifiAPState();
        if(state==13|| state==11){
            wiFiUtils.closeWifiAp();

        }


        wifiname.setText("有线已断开");


        wifipass.setText("");
        if(!NetUtil2.isWifiConnect(context)) {

            boolean ws = wiFiUtils.setWifiEnabled(context);


            if (ws && NetUtil2.isWifiConnect(context)) {

                Message msg = new Message();
                Bundle b = new Bundle();// 存放数据
                b.putString("ssid", "WIFI已连接");
                b.putString("password", "");

                msg.setData(b);
                msg.what = 6;
                mHandler.sendMessage(msg); // 向Handler发送消息,更新UI

            }
        }else{
            Message msg = new Message();
            Bundle b = new Bundle();// 存放数据
            b.putString("ssid", "WIFI已连接");
            b.putString("password", "");

            msg.setData(b);
            msg.what = 6;
            mHandler.sendMessage(msg); // 向Handler发送消息,更新UI


        }
    }


    class MyThread implements Runnable {
        public void run() {


            try {
                wiFiUtils = WiFiUtils.getInstance(context);
                int state = wiFiUtils.getWifiAPState();
                if (state == 13) {

                    Message msg = new Message();
                    Bundle b = new Bundle();// 存放数据
                    b.putString("ssid", wiFiUtils.getValidApSsid());
                    b.putString("password", wiFiUtils.getValidPassword());

                    msg.setData(b);
                    msg.what = 2;
                    mHandler.sendMessage(msg); // 向Handler发送消息,更新UI
                }
            } catch (Exception e) {

            }
        }
    }

    //在主线程里面处理消息并更新UI界面
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    long sysTime = System.currentTimeMillis();
                    CharSequence sysTimeStr = DateFormat.format("MM月dd日 hh:mm", sysTime);
                    tvTime.setText(sysTimeStr); //更新时间
                    break;
                case 2:

                    Bundle b2 = msg.getData();
                    String ssid = b2.getString("ssid");
                    String password = b2.getString("password");


                    wifiname.setText("WiFi:" + ssid);


                    wifipass.setText("密码:" + password);
                    break;
                case 3:
                    Bundle b3 = msg.getData();
                    String temp = b3.getString("temp");
                    String weathers = b3.getString("weather");
                    String week = b3.getString("week");

                    Log.d("getWether", "onResponse: " + weathers + temp + "℃");
                    weather.setText(weathers + temp + "℃  " + week);
                    break;
                case 4:
                    Bundle b4 = msg.getData();
                    String boxId = b4.getString("boxId");

                    Log.d("box", "onResponse: " + boxId);
                    boxIdView.setText(boxId);

                    String imageUrl = b4.getString("logo");

                    if (imageUrl != null && imageUrl.length() > 0) {

                        setImageURL(imageUrl);

                    }
                    break;

                case 5:


                    bgimage.setImageBitmap((Bitmap) msg.obj);

                    break;
                case 6:

                    Bundle b6 = msg.getData();
                    String ssid6 = b6.getString("ssid");
                    String password6 = b6.getString("password");


                    wifiname.setText(ssid6);


                    wifipass.setText("" + password6);
                    break;
                case 7:

                    Bundle b7 = msg.getData();
                    String ssid7 = b7.getString("ssid");
                    String password7 = b7.getString("password");


                    wifiname.setText(ssid7);


                    wifipass.setText(password7);
                    break;
                default:
                    break;

            }
        }
    };

    public List<AppBean> getAllApk() {
        List<AppBean> appBeanList = new ArrayList<>();
        AppBean bean;
        PackageManager packageManager = getPackageManager();
        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        for (PackageInfo p : list) {
            bean = new AppBean();
            bean.setAppIcon(p.applicationInfo.loadIcon(packageManager));
            bean.setAppName(packageManager.getApplicationLabel(p.applicationInfo).toString());
            bean.setAppPackageName(p.applicationInfo.packageName);
            bean.setApkPath(p.applicationInfo.sourceDir);
            File file = new File(p.applicationInfo.sourceDir);
            bean.setAppSize((int) file.length());
            int flags = p.applicationInfo.flags;
            //判断是否是属于系统的apk
            if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                bean.setSystem(true);
            } else {
                bean.setSd(true);
            }
            appBeanList.add(bean);
        }
        return appBeanList;
    }
    private long afterTime = 0;
    private long[] mHits = new long[5]; // 数组长度代表点击次数

    private void threeClickFinish() {
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);


//        startActivity(new Intent(Settings.ACTION_SETTINGS));

        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        long now= (SystemClock.uptimeMillis() - 7000);
//        Toast.makeText(this,  mHits[0]+"-按钮-"+now, Toast.LENGTH_SHORT).show();
        System.out.print(mHits[0]+"-按钮-"+now);
        if (mHits[0] >= now) {
//            Toast.makeText(this, "五击返回按钮", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(Settings.ACTION_SETTINGS));
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                Log.d(TAG, "按下导航键<-左键->");

                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                Log.d(TAG, "按下导航键<-右键->");

                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                Log.d(TAG, "按下导航键<-上键->");

                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                Log.d(TAG, "按下导航键<-下键->");
                break;

            case KeyEvent.KEYCODE_BACK:
                Log.d(TAG, "按下导航键<-下键->");
                break;


            case KeyEvent.KEYCODE_MENU:
                Log.d(TAG, "按下导航键<-下键->");

                threeClickFinish();
                break;
            default:

                break;
        }
        if(keyCode==KeyEvent.KEYCODE_BACK){

            return  false;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }

    OnItemSelectedListener mOnItemSelectedListener = new OnItemSelectedListener() {
        @Override
        public void OnItemSelected(View view, int position) {
//            mScrollRecyclerView.smoothHorizontalScrollToNext(position);


//                AppModel appBean = mList.get(position);
//                Intent launchIntent = getPackageManager().getLaunchIntentForPackage(
//                        appBean.getPackageName());
//                if (launchIntent != null) {
//                    startActivity(launchIntent);
//                }

        }
    };

    OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            Log.d(TAG, "<--1--> click position = " + position);

            AppModel appBean = mList.get(position);
            Intent launchIntent = getPackageManager().getLaunchIntentForPackage(
                    appBean.getPackageName());
            if (launchIntent != null) {
                startActivity(launchIntent);
            }

        }
    };

    OnItemLongClickListener mOnItemLongClickListener = new OnItemLongClickListener() {
        @Override
        public void onItemLongClick(View view, int position) {
            Log.d(TAG, "<--2--> Long click position = " + position);
        }
    };

    OnItemKeyListener mOnItemKeyListener = new OnItemKeyListener() {
        @Override
        public void OnItemKey(View view, int keyCode, KeyEvent event, int position) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
                Log.d(TAG, "KEYCODE_DPAD_CENTER");
            } else if (keyCode == KeyEvent.KEYCODE_MENU) {
                Log.d(TAG, "KEYCODE_MENU");
            }
        }
    };
}
